import { useEffect, useState } from 'react';
import { get, cloneDeep } from 'lodash';
import Debounce from 'lodash.debounce';
import { connect } from 'umi';
import { Button, Modal, Tabs, Tree, message } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { useCanvasContext } from '../CanvasContext';
import { getOrgTree, getRoles, getOrgTreeAcct, getAssigneeList } from '../service';
import styles from './RightPannel.less';

const orgImg = require('@/assets/styles/orgImg.png');
const roleImg = require('@/assets/styles/roleImg.png');
const accImg = require('@/assets/styles/accImg.png');

function NodeMember(props) {
  const { wfeditor, dispatch, appId, title } = props;
  const { selectedId } = wfeditor;
  const [loading, setLoading] = useState(false);
  const canvasContext = useCanvasContext();
  const [currentType, setCurrentType] = useState('');
  const [onlySelect, setOnlySelect] = useState(null);
  const [dynamicType, setDynamicType] = useState('');
  const [memberList, setMemberList] = useState([]);
  const [treeData, setTreeData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const handleCancel = () => {
    props.onCancel();
  };

  const handleFormFinish = () => {
    props.onOk(memberList, currentType);
  };

  useEffect(() => {
    setMemberList([]);
    if (props.visible) {
      intNodeMember();
    }
  }, [props.visible]);

  useEffect(() => {
    if (currentType == 'dynamic') handleFetchAcctList('dynamic', memberList);
  }, [dynamicType]);

  const intNodeMember = () => {
    wfeditor.propList.length &&
      wfeditor.propList.forEach((item) => {
        if (item.id == selectedId) {
          if (item.data.approvalType == 'multiSign') {
            changeTypeSelect('acct', []);
            setOnlySelect('acct');
            setCheckedKeys([]);
            setMemberList([]);
          } else {
            setOnlySelect(null);
            if (title == '节点人员') {
              if (item.data.memberList.length) {
                setMemberList(item.data.memberList);
                changeTypeSelect(item.data.memberList[0].type, item.data.memberList);
              } else {
                changeTypeSelect('org', []);
              }
            } else {
              if (item.data.sendList.length) {
                setMemberList(item.data.sendList);
                changeTypeSelect(item.data.sendList[0].type, item.data.sendList);
              } else {
                changeTypeSelect('org', []);
              }
            }
          }
        }
      });
  };

  const handleDeleteMember = (node, i) => {
    let arr = cloneDeep(memberList);
    arr.splice(i, 1);
    setMemberList(arr);
    handleFetchAcctList(currentType, arr);
  };

  const changeTypeSelect = (type, arr) => {
    setTreeData([]);
    if (type == 'dynamic') {
      setCurrentType(type);
      let num = 0;
      if (arr.length) {
        arr.forEach((item) => {
          if (item.type == 'dynamic' && item.key !== 'startUserName') {
            num++;
          }
        });
      }
      if (num) {
        setDynamicType('org');
      } else {
        setDynamicType('acct');
      }
    } else {
      setDynamicType('');
      if (type && arr.length) {
        setCurrentType(type);
        handleFetchAcctList(type, arr);
      } else {
        setCurrentType(type);
        handleFetchAcctList(type, memberList);
      }
    }
  };

  // 初始化成员树
  const handleFetchAcctList = async (type, arr) => {
    let params = {
      systemCode: appId,
    };
    let treeAcctRes;
    switch (type) {
      case 'org':
        treeAcctRes = await getOrgTree(params);
        break;
      case 'role':
        treeAcctRes = await getRoles(params);
        break;
      case 'acct':
        treeAcctRes = await getOrgTreeAcct(params);
        break;
      case 'dynamic':
        treeAcctRes = await getAssigneeList({
          type: dynamicType,
        });
        break;
      default:
        break;
    }
    const { data, code } = treeAcctRes;
    if (code && code == '200') {
      let tree = [];
      switch (type) {
        case 'org':
          tree = intOrgTreeData(data);
          break;
        case 'role':
          tree = intRoleData(data);
          break;
        case 'acct':
          tree = intTreeData(data);
          break;
        case 'dynamic':
          tree = intDynamicData(data);
          break;
        default:
          break;
      }
      setTreeData(tree);
      let selectKeyList = [];
      arr &&
        arr.length &&
        arr.forEach((item) => {
          selectKeyList.push(item.key);
        });
      setCheckedKeys(selectKeyList);
      // setSelectedKeys(selectKeyList);
    }
  };

  const intOrgTreeData = (data) => {
    let treeArr = [];
    data.forEach((item, index) => {
      treeArr.push({
        key: item.orgId,
        title: item.orgName,
        id: item.orgId,
        orgId: item.orgId,
        parentOrgId: item.parentOrgId,
        orgName: item.orgName,
        sort: item.sort,
        orgCode: item.orgCode,
        orgType: item.orgType,
        state: item.state,
        remark: item.remark,
        type: 'org',
        children: item.children ? intOrgTreeData(item.children) : [],
      });
    });
    return treeArr;
  };
  const intRoleData = (data) => {
    let treeArr = [];
    data.forEach((item, index) => {
      treeArr.push({
        key: item.roleId,
        title: item.roleName,
        id: item.roleId,
        createUser: item.createUser,
        createTime: item.createTime,
        updateUser: item.updateUser,
        updateTime: item.updateTime,
        roleId: item.roleId,
        roleName: item.roleName,
        roleDesc: item.roleDesc,
        roleValue: item.roleValue,
        roleDataType: item.roleDataType,
        status: item.status,
        systemCode: item.rolsystemCodeeDesc,
        remark: item.remark,
        type: 'role',
        children: [],
      });
    });
    return treeArr;
  };
  const intTreeData = (data) => {
    let treeArr = [];
    data.forEach((item, index) => {
      let arr = [];
      if (item.acctList) {
        item.acctList.forEach((acctItem) => {
          arr.push({
            key: acctItem.id,
            isMember: true,
            orgId: acctItem.accountId,
            orgName: acctItem.displayName,
            accountName: acctItem.accountName,
            type: 'acct',
          });
        });
      }
      if (item.children) {
        item.children.forEach((childrenItem) => {
          arr.push({
            key: childrenItem.orgId,
            isMember: false,
            orgId: childrenItem.orgId,
            accountName: childrenItem.accountName,
            orgName: childrenItem.orgName,
            type: 'acct',
            acctList: childrenItem.acctList,
            children: childrenItem.children,
          });
        });
      }
      treeArr.push({
        id: item.orgId,
        isMember: item.isMember || false,
        key: item.key || item.orgId,
        title: item.orgName,
        accountName: item.accountName,
        type: 'acct',
        children: intTreeData(arr),
      });
    });
    return treeArr;
  };
  const intDynamicData = (data) => {
    let treeArr = [];
    data.forEach((item, index) => {
      treeArr.push({
        key: item.value,
        title: item.name,
        accountName: item.name,
        name: item.name,
        value: item.value,
        type: 'dynamic',
        children: [],
      });
    });
    return treeArr;
  };

  const onExpand = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue, info) => {
    let type = currentType;
    let checkedNodes = info.checkedNodes;
    let arr = [];
    let idList = [];
    if (type == 'acct') {
      checkedNodes.forEach((item) => {
        if (item.isMember && idList.indexOf(item.id) == -1) {
          idList.push(item.id);
          arr.push(item);
        }
      });
    } else if (type == 'dynamic') {
      if (info.checked) {
        let num = 0;
        memberList.forEach((item) => {
          if (item.type == 'dynamic') {
            num++;
          }
        });
        if (num) {
          arr = cloneDeep(memberList);
          arr.forEach((item) => {
            idList.push(item.key);
          });
        }
        checkedNodes.forEach((item) => {
          if (idList.indexOf(item.key) == -1) {
            idList.push(item.key);
            arr.push(item);
          }
        });
      } else {
        arr = cloneDeep(memberList);
        memberList.forEach((item, index) => {
          if (item.key == info.node.key) {
            arr.splice(index, 1);
          }
        });
      }
    } else {
      checkedNodes.forEach((item) => {
        if (idList.indexOf(item.id) == -1) {
          idList.push(item.id);
          arr.push(item);
        }
      });
    }
    setMemberList(arr);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue, info) => {
    // setCheckedKeys(selectedKeysValue);
  };

  return (
    <>
      <Modal
        title={title}
        visible={props.visible}
        onOk={handleFormFinish}
        width={636}
        okButtonProps={{ disabled: loading, loading: loading }}
        onCancel={handleCancel}
      >
        <div className={styles['member-content']}>
          <div className={styles['member-list']}>
            {memberList &&
              memberList.map((node, i) => {
                return (
                  <div className={styles['member-name-card']} key={node.key}>
                    {node.type == 'org' && <img src={orgImg} />}
                    {node.type == 'role' && <img src={roleImg} />}
                    {node.type == 'acct' && (
                      <div className={styles['member-name-acct']}>{node.title[0]}</div>
                    )}
                    {node.type == 'dynamic' && <img src={accImg} />}
                    <span>{node.title}</span>
                    <CloseOutlined
                      onClick={() => handleDeleteMember(node, i)}
                      style={{ marginLeft: 10, cursor: 'pointer' }}
                    />
                  </div>
                );
              })}
          </div>
          <div className={styles['member-select']}>
            <Tabs activeKey={currentType} onTabClick={changeTypeSelect}>
              <Tabs.TabPane
                disabled={onlySelect ? true : false}
                tab={'组织框架'}
                key={'org'}
              ></Tabs.TabPane>
              <Tabs.TabPane
                disabled={onlySelect ? true : false}
                tab={'角色'}
                key={'role'}
              ></Tabs.TabPane>
              <Tabs.TabPane tab={'成员'} key={'acct'}></Tabs.TabPane>
              <Tabs.TabPane
                disabled={onlySelect ? true : false}
                tab={'动态负责人'}
                key={'dynamic'}
              ></Tabs.TabPane>
            </Tabs>
            {currentType !== 'dynamic' && (
              <Tree
                checkable
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                onCheck={onCheck}
                checkedKeys={checkedKeys}
                onSelect={onSelect}
                selectedKeys={selectedKeys}
                treeData={treeData}
              />
            )}
            {currentType == 'dynamic' && (
              <div className={styles['member-select-dynamic']}>
                <div className={styles['member-select-type']}>
                  <div
                    onClick={() => {
                      setDynamicType('acct');
                    }}
                    className={dynamicType == 'acct' ? styles['member-select-type-active'] : ''}
                  >
                    流程发起人
                  </div>
                  <div
                    onClick={() => {
                      setDynamicType('org');
                    }}
                    className={dynamicType == 'org' ? styles['member-select-type-active'] : ''}
                  >
                    主管
                  </div>
                </div>
                <div className={styles['member-select-level']}>
                  <Tree
                    checkable
                    onExpand={onExpand}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    onCheck={onCheck}
                    checkedKeys={checkedKeys}
                    onSelect={onSelect}
                    selectedKeys={selectedKeys}
                    treeData={treeData}
                  />
                </div>
              </div>
            )}
          </div>
        </div>
      </Modal>
    </>
  );
}

export default connect(({ user, applicationConfig, loading }) => ({
  userInfo: user.userInfo,
  projectTypeList: applicationConfig.projectTypeList,
  loading,
}))(NodeMember);
